
\chapter{Pattern Enforcer}
\label{chap:pattern-enforcer}
Pattern Enforcer is a tool that verifies selected structural aspects of 
design patterns. There are several built-in patterns, but users can also 
add their custom patterns using the special API. Pattern Enforcer needs to 
know which classes are supposed to implement which pattern in order to 
enforce its correct implementation. For this purpose the Patterns4Net 
special documentation for pattern solution participants is used.

This chapter starts with the explanation of Patterns4Net -- the common 
infrastructure for Pattern Enforcer and Architecture Explorer. 
Patterns4Net handles discovering of the patterns meta-data and 
representation of design patterns instances. Then the description of 
Pattern Enforcer tool itself follows.

%-------------------------------------------------------------------------------------------------
%-------------------------------------------------------------------------------------------------
%-------------------------------------------------------------------------------------------------
\section{Design patterns documentation}
\label{sec:dpdocumentation}

%-------------------------------------------------------------------
%-------------------------------------------------------------------
\subsection{Terminology}
Design pattern is an abstract entity, which, among other things, primarily describes 
a solution to a recurring problem. The description of the solution usually 
contains a certain degree of flexibility. If such design pattern is 
implemented by a developer, he transforms the abstract ideas behind the pattern 
into a real source code. For example, participants of the \pattern{Composite} 
pattern are transformed into the concrete classes in a real source code, or a method 
for the creation of a \pattern{Product} object, 
described in the \pattern{Factory Method} pattern, is implemented by a 
concrete method. When the participants of 
a certain pattern are implemented by the concrete elements in a source code, 
we will say that these elements form an instance of the pattern. 
For better illustration, an instance of the \pattern{Composite} 
pattern is given in the figure~\ref{fig:composite}. 
From the structural point of view the \pattern{Composite} pattern has two roles: 
the \pattern{Composite} class (in this particular instance represented by 
the \inlinecode{WidgetComposition} class) and the \pattern{Component} interface 
(in this case, the \inlinecode{IWidget} interface), which should by implemented 
by the \pattern{Composite} class. 
	\begin{figure}[h]				
		\begin{lstlisting}[language=C]
public class WidgetComposition : IWidget
{
	private IList<IWidget> children;
	public int Width {
		get { return children.Sum(x => x.Width); }
	}
}
		\end{lstlisting}		
		\caption{Example of the \pattern{Composite} pattern instance.}
		\label{fig:composite}
	\end{figure}

\subsection{Documentation of pattern instances}
If we consider the example from the figure~\ref{fig:composite}, 
Pattern Enforcer doesn't know that the \inlinecode{WidgetComposition} class 
should implement the \pattern{Composite} pattern, and therefore 
Pattern Enforcer doesn't know that it should enforce the structural aspects 
of the correct implementation of the \pattern{Composite} pattern on the 
\inlinecode{WidgetComposition} class. For this purpose we need to 
create a mapping between concrete elements in a source code and the 
pattern participants they are supposed to implement. We call 
this mapping as a design patterns participants mapping. 

Since Patterns4Net and therefore Pattern Enforcer works with .NET assemblies 
the design patterns participants mapping can be created from  
any data included in .NET assemblies. It can be constructed from naming 
conventions, for example, classes whose name starts with "Null" can be 
said to be implementation of the \pattern{Null Object} pattern; or the 
mapping can be constructed from special meta-data added into the .NET 
assembly by it's author in order to explicitly document his intentions to 
implement such and such pattern. We call this kind of meta-data as 
patterns meta-data.

Patterns4Net provides an extensible mechanism for construction of design patterns 
participants mapping from .NET assemblies data. At the moment it supports 
pattern meta-data expressed as .NET attributes. Class that plays the 
main role in particular design pattern implementation is decorated 
with a special attribute and references to classes that implement another 
roles in the pattern solution, if there are any, can be inserted as arguments 
for this attribute. For better illustration, a code example is provided in 
the figure~\ref{fig:patterninstanceexmple}. Here the 
\inlinecode{WidgetComposition} class is 
decorated with the \inlinecode{Composite} attribute, which also allows us to 
provide a \pattern{Component} type as a constructor parameter. Explicit 
specification of a \pattern{Component} type is required when a 
\pattern{Composite} class implements more than one interface, 
otherwise the \pattern{Component} type can be inferred automatically.
	\begin{figure}[h]				
		\begin{lstlisting}[language=C]
using Patterns4Net.Attributes;
[Composite(typeof(IWidget))]
public class WidgetComposition : IWidget, ICloneable
{
	private IList<IWidget> children;
	public int Width {
		get { return children.Sum(x => x.Width); }
	}
	// ...
}
		\end{lstlisting}		
		\caption{An example of attributes driven documentation of pattern instances.}
		\label{fig:patterninstanceexmple}
	\end{figure}
	
%-------------------------------------------------------------------
%-------------------------------------------------------------------	
\subsection{Pattern instances representation}
In order to use the design patterns participants mapping, Patterns4Net 
needs to have data structures that represent the mapping. For this purpose 
standard C\# classes are used and instances of these classes represent 
the instances of design patterns. An object that represents a pattern instance 
provides a name of the pattern, and the references to the elements that 
participate in this pattern instance. For example, the object that 
represents the \pattern{Composite} pattern instance from the figure 
\ref{fig:patterninstanceexmple} returns the string 
\inlinecode{"Composite"} as the pattern name and it provides 
references to the \inlinecode{WidgetComposition} as the \pattern{Composite} 
class role and to the \inlinecode{IWidget} interface as the \pattern{Component} 
interface. Each pattern has a specific set of participants and therefore 
for each pattern, there is a specific class.

The classes for the pattern representation provide the name of the pattern and 
the references to the pattern instance participants as standard .NET properties. 
The references to code elements (that is classes, interfaces, methods, etc.) 
are represented by instances of Mono Cecil's classes, 
which are similar to the \inlinecode{System.Type} type from the standard library
(e.g. \inlinecode{TypeReference},~\cite{cecil:Online}). 
Mono Cecil's types are used, because we use Mono Cecil for parsing 
of .NET assemblies\footnote{Reasons why we have chosen Mono Cecil 
and more detailed information about it are 
presented in the subsection~\ref{subsec:cil}}. 
The figure~\ref{fig:compositedef} demonstrates an example of the \pattern{Composite} 
pattern definition. 
	\begin{figure}[h]				
		\begin{lstlisting}[language=C]
public class Composite : IPattern
{
	public TypeDefinition Composite { get; set; }
	public TypeReference Component { get; set; }
	// The Name is required by IPatter interface
	public string Name { 
		get { return "Composite"; } 
	}
}
		\end{lstlisting}		
		\caption{The \pattern{Composite} pattern definition for Patterns4Net.}
		\label{fig:compositedef}
	\end{figure}

	
%-------------------------------------------------------------------------------------------------
%-------------------------------------------------------------------------------------------------
%-------------------------------------------------------------------------------------------------	
\section{Patterns structural constraints specification}
There are two possibilities to capture the structural constraints of a particular 
pattern that should be verified by Pattern Enforcer. The constraints can be 
hard-coded in the Patter Enforcer itself, 
or they can be located in external files 
and expressed in a special language, which would ease the addition 
of constraints for new design patterns. 

We used a compromise approach in Pattern Enforcer. We developed a special 
C\# API for the specification of the structural aspects of design patterns, 
therefore the specification itself is expressed in a standard C\# 
(or any other .NET language) code, but the author of the specification 
is provided with a set of classes and methods that ease this task. 
The code that expresses the specification can be then loaded into 
Pattern Enforcer at runtime using the standard .NET mechanisms designated 
for this purposes.
When we made this decision, we had considered several important consequences: 
the authors of the specification will be able to use the provided API 
or, if the API is not sufficient for their purposes, they can take 
the advantage of the full power of C\#. We didn't have to develop a 
parser for a special language; and, since the users of Pattern Enforcer 
are .NET programmers, they will learn the C\# API with less effort 
than a new syntax of a special language.

In the rest of this section we describe the API for the patterns structural 
constraints specification in more detail. Because this API can be 
considered as an example of so called Domain Specific Language 
(DSL, \cite{fowler2010domain}) and because it also uses a technique 
called Fluent API, we discuss these two concepts in the following subsection.

%-------------------------------------------------------------------
%-------------------------------------------------------------------
\subsection{Domain specific languages}
Domain Specific Language (DSL) is a computer programming language of limited 
expressiveness focused on a particular domain. There are two types of DSLs: 
internal and external. The external DSLs are completely new languages with their 
own custom syntax, while the internal DSLs are embedded into existing general 
purpose language such as C\#, Java or Ruby by providing specific public API. 
When developing an embedded DSL, a programmer do not have to create a 
parser for his DSL, but he can be limited by the syntax of the "hosting" 
language.

In the connection with the embedded DSLs, the term type-safe DSL is often used. 
Type-safe DSLs use constructs that can be verified by a compiler rather than 
strings with a special internal syntax that can be verified only during 
the runtime or by an additional tool. For example, NHibernate ORM framework 
(\cite{nhibernate:Online})
has such API for a definition of objects to database schema mapping. 
Instead of expressing the names of properties as strings, 
NHibernate exploits the C\#'s feature of lambda expressions for this purpose, 
and thus the existence of the properties used in the mapping is verified 
by the C\# compiler. For a better idea of this approach, 
figure~\ref{fig:nhibapi} shows a short example of the NHibernate DSL usage in 
C\#. Note that all text in this figure forms a 
perfectly valid C\# code, although it may seem as a special language.
	\begin{figure}[h]				
		\begin{lstlisting}[language=C]
var mapper = new ModelMapper();
mapper.Class<RegisteredUser>(mapping =>
{
    mapping.Id(x => x.Id, map => map.Column("MyClassId"));
    mapping.Property(x => x.Username, map => map.Length(150));
});
		\end{lstlisting}		
		\caption{Example of type safe DSL embedded into the C\# language.}
		\label{fig:nhibapi}
	\end{figure}

The usage of type safe DSLs also enables integrated development environments 
support. Namely intellisense support can make the development more effective 
and can bring a better experience for developers who don't know the DSL syntax yet, 
because they can see all the possibilities in the intellisense window together 
with their API documentation. On the other hand, after every change, the code 
has to be recompiled and the assembly must be deployed, which is not always 
possible. An xml based configuration or an external DSL might provide more 
flexible solution in such case. 

Embedded DSLs usually leverage a technique called Fluent API, which means 
that a method returns an object on which a user is expected to invoke another 
method. This chaining of methods can make the API more self describing, 
because methods names and their arguments names can be then read almost 
as an English sentence. An example of the Fluent API from jMock, 
a mock object library for Java~\cite{jmock:Online}, 
is show in figure~\ref{fig:fluentapi}. 
	\begin{figure}[h]				
		\begin{lstlisting}[language=C]
mock.expects(once())
  .method("m")
  .with(stringContains("hello"));
		\end{lstlisting}		
		\caption{An example of methods chaining in Fluent API.}
		\label{fig:fluentapi}
	\end{figure}
	
%-------------------------------------------------------------------
%-------------------------------------------------------------------
\subsection{The API for pattern constraints specification}
\label{subsec:constraintsapi}
Because we have a strongly typed representation of design patterns instances, 
we can build a type safe DSL for their constraints specification, where 
we will use lambda expressions in a similar way as the authors of NHibernate.

In our conception, a constraint is any boolean function that takes a pattern 
instance as a parameter and returns a boolean value, which indicates whether 
the pattern instance conforms to the constraint or not. However, 
Pattern Enforcer provides a DSL to make the specification of these constraints 
easier than that. 
The key part is that it enables to specify the constraints as lambda functions. 
We call such function a "check". 

A check may be performed on the whole 
pattern instance, then the parameter of the lambda function will be the 
object representing the pattern. 
These checks may verify the relations between roles, 
for example, that the \pattern{Composite} class implements the 
\pattern{Component} interface. Users can also set up checks only for a 
specific role of a pattern instance. In such case, the Pattern Enforcer API 
provides a method to select the specific property of the pattern instance object 
with a lambda function the same way NHibernate uses lambda functions 
for selecting properties. After the property is selected, the user can create 
a check only for the value of the selected property (that is for a particular role). 
Finally the user can also select specific methods of the selected role to provide 
a check for each of them. The selection of these methods is also done using 
a lambda filter function. 

To summarize it all up: users can 
select a subject of the check, using lambda functions, and then they can enter 
the check itself again as a lambda function, which takes the subject of the 
check as a parameter. For a better idea, an example is 
shown in figure~\ref{fig:selectionapi}.
	\begin{figure}[h]				
		% ,linenos=true
		\begin{lstlisting}[language=C]
// we want to work with the Composite role
this.Type(composite => composite.Composite)	
// we want to check all its non-private methods
.Methods(method => method.IsPublic || method.IsProtected) 
// on each of them, we perform the following check
.Check((composite, method) => 
			method.CallsAnyOf(pattern.Component),
	(composite, method) => "An error in " + method.Name));
		\end{lstlisting}		
		\caption{An example of constraints configuration in Pattern Enforcer.}
		\label{fig:selectionapi}
	\end{figure}

A check expression might be anything, which enables wide range of possibilities 
for experienced users, but Pattern Enforcer provides an easy to use extensions 
to underlying Mono Cecil's API. \inlinecode{CallsAnyOf} is an example of such 
extension, which returns \inlinecode{true} iff the method invokes a member 
of given class. Basically these extensions are designed to enable 
straightforward specification of most of the predicates presented in 
the section~\ref{sec:patterns-formalization}.

%-------------------------------------------------------------------
%-------------------------------------------------------------------
\subsection{Built-in patterns}
\label{subsec:builtinpatterns}
As we claim in the section~\ref{sec:patterns-formalization} constraints for 
the built-in patterns were chosen rather less restrictively than in the other 
tools of this type. The aim was to enforce those aspects that are strongly 
significant to given pattern and the implementation without them cannot be 
clearly called as an implementation of this pattern. For example, the 
\pattern{Factory Method} pattern, whose main participant is the 
\patternrole{Factory Method} itself, would make no sense if the actual 
\patternrole{Factory Method} was void. On the other hand, to enforce that the 
method's body contains only a constructor invocation and a return statement, 
seems to us as an inappropriate restriction, because the developer 
might want to prepare some data structures before returning the \patternrole{Product} 
of the \pattern{Factory Method}. A list of patterns supported by 
Pattern Enforcer can be found in the appendix~\ref{app:patternslist}.

The relatively unrestrictive API for patterns constraints specification allows us 
to provide more advanced verification than only verification of 
structural aspects. This is the case of the \pattern{Immutable} pattern. 
The verification of it's implementation checks that the \pattern{Immutable} 
class does not allow to change the internal state of it's instance once it is 
available to the "outside world". What does this bring us? A simple immutability 
in C\# can be enforced by specifying all the class's 
fields as \inlinecode{readonly}, but 
this disables the creator of the class to provide a 
\pattern{Simple Factory Method} that would do some changes to 
the \pattern{Immutable} class instance before the method 
returns it to the "outside world". Also auto-implemented 
properties, which bring a notable simplification of implementation of 
simple properties, cannot be specified as \inlinecode{readonly}. 

We will illustrate the process of choosing the structural constraints that 
should be verified by Pattern Enforcer on the example of the 
\pattern{Template Method} pattern and the \pattern{Adapter} pattern. 

\paragraph*{Template Method}
\subparagraph*{}
The main role of the \pattern{Template Method} pattern is a 
\pattern{template method}, which defines the skeleton of an algorithm. 
The \pattern{template method} invokes one or more virtual methods, 
which are expected to implement certain steps of the algorithm. 
Because these methods are virtual, one can override them in a sub-class 
and thus alter some steps of the algorithm without the need to write the whole 
algorithm from scratch. 

The core of the \pattern{Template Method} pattern are invocations of 
virtual methods that can alter the algorithm. From a first look, one could say
we should enforce that the \pattern{template method} invokes at 
least one virtual method.  However, a \pattern{template method} that 
invokes another non-virtual method that then invokes another virtual method 
can be considered as an implementation of the \pattern{Template Method} pattern 
as well, because it also allows us to alter the algorithm in sub-classes. 
We can recursively check all methods that are invoked from 
our \pattern{template method}, but it would be unsystematic. Instead, a simple 
observation can help: non-virtual methods that invoke virtual methods are 
usually also implementation of the \pattern{Template Method} pattern. 
So the conclusion is that a \pattern{template method} should invoke at least 
one virtual method or at least one another \pattern{template method}. 

It is considered a good practice with the \pattern{Template Method} pattern 
to declare the \pattern{template method} as non-virtual (sealed) and so we 
enforce this too. 

The specification of constraints for the \pattern{Template Method} pattern 
is shown in figure~\ref{fig:templmethod} (we stripped out the full 
error messages from it). As a first step we check that 
the type that declares the \pattern{template method} is not sealed and 
therefore it can be sub-classed. If this is fulfilled, we check that 
the template method calls at least one virtual method or another 
template method. 
	\begin{figure}[h]				
		\begin{lstlisting}[language=C] %small listing
// check that declaring type is not sealed:
this.Type(pattern => pattern.TargetMethod.DeclaringType)
  .Check(type => type.IsSealed == false,
         (pattern, type) => "...error message...");

// check that template method invokes at least 
// one virtual method or another template method:
this.If(pattern => !pattern.TargetMethod.DeclaringType.IsSealed)
  .Method(pattern => pattern.TargetMethod)
  .Check(
    method => 
      method.GetMethodCalls().Any(
        call =>
          call.TargetObject != null &&
          call.TargetObject.IsThisParameter &&
          (IsTemplateMethod(call.Method) ||
           call.Method.Resolve().IsOverriddeable())),
    (pattern, method) => "...error message...");
		\end{lstlisting}		
		\caption{The specification of the built-in \pattern{Template Method} pattern.}
		\label{fig:templmethod}
	\end{figure}

	
\paragraph*{Adapter}
\subparagraph*{}
The \pattern{Adapter} pattern solves the problem of two 
incompatible interfaces: the \pattern{Target} interface and 
the \pattern{Adaptee} interface. It suggest to create an \pattern{Adapter} 
class that uses the \pattern{Adaptee} interface and adapts it to the 
\pattern{Target} interface. The most usual implementation of this pattern 
is done by implementing the \pattern{Target} interface by the \pattern{Adapter} 
class, which holds an instance of the \pattern{Adaptee} interface as a 
private field and delegates operations to it. 

Only in rare cases the \pattern{Adapter} class just delegates all it's 
operations to the \pattern{Adaptee}. Usually it is needed to convert either 
parameters values or a return method value. The \pattern{Target} interface might not 
have the same number of methods as the \pattern{Adaptee}, therefore some 
\pattern{Target}'s methods might be delegated to more than one 
\pattern{Adaptee}'s method; or a \pattern{Target}'s method might not have 
a corresponding method in the \pattern{Adaptee}, so it is performed by the 
\pattern{Adapter} class without any help from the \pattern{Adaptee}. 

It would be very difficult or almost impossible to capture some useful 
constraints about methods delegation in this case. The \pattern{Adapter} 
pattern is one of the patterns whose solution contains a certain degree 
of flexibility. One possibility is to enforce that the \pattern{Adapter} class 
delegates at least one operation to the \pattern{Adaptee}, but 
when the \pattern{Adapter} class has a field of the \pattern{Adaptee} type 
and does not use it at all, the programmer will be anyway warned by 
the compiler. Therefore the only two constrains that seems to us as useful, 
but still does allow the flexibility in the implementation of 
the \pattern{Adapter} pattern, are: the \pattern{Adapter} class should have 
at least one field of the \pattern{Adaptee} type, and the \pattern{Adapter} 
class should implement or inherit the \pattern{Target} interface. 

Another special case appears when the implementation of the 
\pattern{Adapter} pattern does not adapt an interface of a class, 
but, for example, a procedural interface or an interface to a device. 
In such case we cannot enforce even existence of the field of the correct type. 
Similarly when the \pattern{Target} interface is not standard .NET 
interface, we cannot enforce that the \pattern{Adapter} class implements it. 
Therefore, we allow users to omit the \pattern{Target} or \pattern{Adaptee} types. 
If they do so, nothing is enforced, but the documentation of patterns 
participants is still useful for Architecture Explorer. 

The final specification of constraints for the \pattern{Adapter} pattern 
is given in the figure~\ref{fig:adapterconstrspec}.
	\begin{figure}[h]				
		\begin{lstlisting}[language=C] %small listing
this.If(pattern => pattern.TargetInterface != null)
  .Check(pattern => pattern.WrapperType.Implements(pattern.Target),
         pattern => "...error...");

this.If(pattern => pattern.WrappedType != null)
  .Check(HasFieldOfType, 
         pattern => "...error...");
		 
// ...
static bool HasFieldOfType(Adapter pattern)
{
  return pattern.WrapperType.HasFields &&
    pattern.WrapperType.Fields.Any(x => 
        x.FieldType.IsEqual(pattern.WrappedType));
}
		\end{lstlisting}		
		\caption{The specification of the built-in \pattern{Adapter} pattern.}
		\label{fig:adapterconstrspec}
	\end{figure}

	

%-------------------------------------------------------------------------------------------------
%-------------------------------------------------------------------------------------------------
%-------------------------------------------------------------------------------------------------
\section{Usage}
\label{sec:patternenforcerusage}
If a user wants to take advantage of Pattern Enforcer, one possible way to 
achieve it is to decorate his types with pattern attributes. 
For this, it is required to add a reference 
to the \emph{Patterns4Net.Attributes.dll} assembly in the project. This 
assembly contains only the attributes definitions, thus it's footprint should be 
minimal. It is built for .NET version 2.0, so Pattern Enforcer can be basically 
used in projects built for older versions of the .NET. 
When the reference is added, the types can be decorated with patterns 
attributes from the namespace \inlinecode{Patterns4Net.Attributes}.
	\begin{figure}[h]				
		\begin{lstlisting}[language=C]
using Patterns4Net.Attributes;
[Composite(typeof(IWidget))]
public class WidgetComposition : IWidget, ICloneable
{
	private IList<IWidget> children;
	int IWidget.Width {
		get { return 10; }
	}
	// ...
}
		\end{lstlisting}		
		\caption{An example of an annotated implementation of the \pattern{Composite} pattern.}
		\label{fig:wrongcomposite}
	\end{figure}
	
The figure~\ref{fig:wrongcomposite} contains an annotated implementation 
of the \pattern{Composite} pattern, which is not valid, because the getter 
method of the \inlinecode{Width} property is not using the 
\inlinecode{children} collection. 

Pattern Enforcer can be run outside the Visual Studio or inside the Visual Studio. 
When the Visual Studio project is built, there should be a resulting assembly 
in the output folder (usually \{project folder\}\textbackslash{}bin\textbackslash{}Debug). 
Say it's name is \emph{EnforcerExample.dll}. 
Then if the \emph{pattern-enforcer.exe} is run from the command line supplied with  
a path to \emph{EnforcerExample.dll} as an argument, it should produce the output 
shown in the figure~\ref{fig:enforcercmd}. Pattern Enforcer supports three 
output formats: plain text, xml and special format for Visual Studio. 
The output format could be specified with a command line option. 
When Pattern Enforcer is run without arguments, it displays the help.
	\begin{figure}
		\mbox{\includegraphics[width=\textwidth]{images/enforcer-cmd.png}}
		\caption{The output of Pattern Enforcer for the \inlinecode{WidgetComposition} class.}
		\label{fig:enforcercmd}
	\end{figure}

Besides the direct execution of \emph{pattern-enforcer.exe}, Pattern Enforcer 
can be integrated more tightly into the build process in Visual Studio. 
Visual Studio project files are basically MSBuild scripts, 
so the only thing a user has to do is to add a reference to Pattern 
Enforcer MSBuild task and invoke it in the AfterBuild target, which, as 
its name indicates, gets always executed after the source code is built.
To enable this integration, it is needed to to open the project file 
\emph{EnforcerExample.csproj} in any text editor, find the xml root 
element \inlinecode{Project} and just below it, insert a 
\inlinecode{UsingTask} tag, where the location of 
the \emph{PatternEnforcer.MSBuildTask.dll} assembly should be specified. 
Next, the AfterBuild target should be located (it should be commented out and 
placed near the end of the file), it should be uncommented, 
and an invocation of the Pattern Enforcer task should be inserted as 
it's child element. The figure~\ref{fig:msbuild} shows the xml code fragment 
and also a screenshot of Visual Studio displaying the warnings.
	\begin{figure}[h]				
		\begin{lstlisting}[language=XML]
<Project ToolsVersion="4.0" DefaultTargets="..." xmlns="...">
  <!-- Includes the PatternEnforcerTask -->
  <UsingTask TaskName="PatternEnforcerTask" 
    AssemblyFile=".\a\path\to\PatternEnforcer.MSBuildTask.dll"/>
  
  <!-- ... -->
  <PropertyGroup>
    <PatternAssemblies>
      $(OutputPath)/$(AssemblyName).dll;
    </PatternAssemblies>
  </PropertyGroup>    
  <Target Name="AfterBuild">
    <PatternEnforcerTask 
      ToolPath="..\a\path\to\pattern-enforcer-executable\" 
      ConfigFile=".\enforcer-config.xml"
      ShowErrorsAsWarnings="true"
      InputAssemblies="\$(PatternAssemblies)">
    </PatternEnforcerTask>  
  </Target>  
</Project>
		\end{lstlisting}		
		\includegraphics[width=\textwidth]{images/enforcer-vs-errors.jpg}
		\caption{Integration of Pattern Enforcer and Visual Studio 2010.}
		\label{fig:msbuild}		
	\end{figure}
	
Checking by Pattern Enforcer can be turned off for a specific element by 
annotating it with a special attribute \inlinecode{PatternEnforcerIgnoreAttribute}, 
which has a string property \inlinecode{Justification}, where developers 
should provide a description why they have disabled the checks on this class or 
method.

\subsection{Unit tests}
The second possible way of taking advantage of Pattern Enforcer does not 
require to annotate classes with pattern attributes. Instead the relation 
between a concrete pattern and it's roles is constructed by hand 
in an automatized test. 
Pattern Enforcer provides the \inlinecode{PatternEnforcerContext} class whose 
instance represents an assembly loaded into memory and prepared for 
execution of Pattern Enforcer checks. It is recommended to set up this 
object in the test fixture\footnote{This term is used by the NUnit 
framework (\cite{nunit:Online}), some of other xUnit frameworks also use 
the term "test suite" instead of a test fixture.}
set up method, which is a method that gets executed only once 
before any test from the test fixture is executed. 
The \inlinecode{PatternEnforcerContext} provides a method \inlinecode{AssertThat}, 
which has one generic parameter. This method returns an object that provides 
methods with names Is\{PatternName\}, which perform the check of 
conformance to given pattern. The type selected as the generic argument 
of the call to 
\inlinecode{AssertThat} is used as main role of the pattern, other additional 
required information, if needed, are supplied as parameters of the 
Is\{PatternName\} method. The figure~\ref{fig:testfixture} shows an 
example of such test fixture using the NUnit framework (\cite{nunit:Online}).
	\begin{figure}[h]				
		\begin{lstlisting}[language=C] %small listing
[TestFixture]
public class WidgetCompositionTests : IWidget, ICloneable
{
  private PatternEnforcerContext patternEnforcer;
  [FixtureSetUp]
  public void SetUpFixture() {
    this.patternEnforcer = 
      PatterEnforcerContext.Create("EnforcerExample.dll");
  }  
  [Test]
  public void WidgetComposition_Is_Composite() {
    this.patternEnforcer
      .AssertThat<WidgetComposition>()
      .IsComposite(typeof(IWidget));
  }
}
		\end{lstlisting}		
		\caption{Example of an automatized test that invokes Pattern Enforcer.}
		\label{fig:testfixture}
	\end{figure}

\subsection{Specification of custom pattern}
There are two possibilities to define a pattern and constraints that will be 
enforced on it's implementation. The first one is more complex, but provides 
better flexibility, and thus is used internally by Pattern Enforcer. The 
second one is more simple and is designed to provide an easier instrument to 
create user-defined patterns. The first approach is described in the 
section~\ref{subsec:patternsrepre}. Here we show how to use the second one. 

We describe an example of an implementation of a simple custom pattern from 
a user perspective. We will call our new pattern as the \pattern{Base Caller}. 
It has two roles: the Target class and the Target's base class. The constraint 
we specify for this pattern is that the Target class is required 
to invoke the corresponding base methods in the bodies of overridden methods. 
We describe how to create a class that represents 
our pattern and attribute for it's documentation, 
then we specify the constraints for our new pattern 
and then we show how to load our new pattern into Pattern Enforcer.

\paragraph{Representation of custom pattern}
\subparagraph*{}
A custom pattern is represented by a class that implements 
the \inlinecode{IPattern} interface and it is also recommended to implement the 
\inlinecode{IPatternAttribute} interface, which is just a marker for pattern 
attributes. This class is used for representation of the pattern and at the same 
time as an attribute for annotating the pattern instances in code, 
therefore it should inherit from the \inlinecode{Attribute} class from standard 
.NET library.

The \inlinecode{IPattern} interface requires just 
a getter of the property named \inlinecode{Name} and a getter of the 
\inlinecode{AbstractionLevel} property, which is used by Architecture 
Explorer (for now, \inlinecode{null} can be used as a default value). 
The value of the \inlinecode{Name} property should be a human readable name 
of the pattern, which may contain any characters including 
spaces. The \inlinecode{IPattern} interface does not require any other 
properties, but the creator of the pattern should add other properties for 
representing the pattern participants, in this case the Target and 
it's base class. Because these properties should contain references to 
other types, they will be of type \inlinecode{TypeDefinition}. 
The implementation is shown in the figure~\ref{fig:custompattern1}.
	\begin{figure}[h]				
		\begin{lstlisting}[language=C]
public class BaseCaller : Attribute, IPattern, IPatternAttribute
{
	string IPattern.Name {
		get { return "Base Caller"; }
	}	
	public TypeDefinition TargetType { get; set; }
	public TypeDefinition BaseType { get; set; }
}
		\end{lstlisting}		
		\caption{The implementation of custom user-defined pattern.}
		\label{fig:custompattern1}
	\end{figure}

\paragraph{Implementation of the \pattern{Base Caller} attribute}
\subparagraph*{}
During the processing of patterns attributes, Patterns4Net needs to 
reconstruct the \inlinecode{BaseCaller} attribute instance from CIL meta-data. 
The meta-data does not contain an instance of the attribute, 
instead it contains only values of constructor arguments used for its 
instantiation in the original source code and names and the values of 
the properties that were assigned. 
For example, meta-data for the standard .NET \inlinecode{Obsolete} 
attribute as it is used in the figure~\ref{fig:attributeexample} contains: 
zero constructor arguments, because the parameterless constructor 
of the \inlinecode{Obsolete} attribute is used; and one property with 
name \inlinecode{Message} and it's value.
	\begin{figure}[h]				
		\begin{lstlisting}[language=C]
[Obsolete(Message="A constant value")]
public class AnnotatedClass
{
}
		\end{lstlisting}		
		\caption{A code example to illustrate CIL metadata for attributes.}
		\label{fig:attributeexample}
	\end{figure}

For the purpose of the reconstruction of pattern attributes from CIL meta-data, 
classes that implement both the pattern and it's attribute are required to 
define a constructor with one parameter of type \inlinecode{IDictionary<string, object>}
\footnote{More technical reasons that lead to this decision are given in 
section~\ref{sec:enforcer-architecture}}. The pattern attribute class should 
be able to reconstruct it's instance from this dictionary, which provides the CIL 
meta-data in the following format:
\begin{itemize}
	\item{Constructor Arguments -- indexed by the number of the position. 
	For example, the first argument, if any, will be under the index \inlinecode{"0"}.}
	\item{Attribute's target -- a \inlinecode{TypeReference} instance that 
	contains a reference to the type that was decorated with this attribute. 
	This value is available under the index \inlinecode{"-Target"}.}	
	\item{Assigned properties -- the remaining entries of the dictionary are name-value 
	pairs representing the properties. If the original property is of type 
	\inlinecode{System.Type}, than it's actual value in the dictionary will 
	be \inlinecode{TypeReference} from Mono Cecil 
	referring to the same type.}		
\end{itemize}

The implementation of such constructor for the \inlinecode{BaseCaller} class 
is shown in the figure~\ref{fig:basecallerctor}. (Note: an instance of 
the \inlinecode{TypeReference} class from Mono Cecil can be converted to 
the corresponding \inlinecode{TypeDefinition} instance using method 
\inlinecode{Resolve()} as in the example.)
	\begin{figure}[h]				
		\begin{lstlisting}[language=C]
public class BaseCaller : Attribute, IPattern, IPatternAttribute
{
  public BaseCaller(IDictionary<string, object> values) {
    var targetRef = (TypeDefinition)values["-Target"];
    this.TargetType = targetRef.Resolve();
    this.BaseType = this.TargetType.BaseType.Resolve();
  }
  // ... as before
}
		\end{lstlisting}		
		\caption{The implementation of a special constructor required by Patterns4Net.}
		\label{fig:basecallerctor}
	\end{figure}
	
\paragraph{Constraints specification}
\subparagraph*{}
The pattern attribute, as declared in figure~\ref{fig:basecallerctor}, can be used 
for annotation of classes that implement our \pattern{Base Caller} pattern. 
However, to verify that such class invokes corresponding base methods in 
overridden methods bodies, the last two things are needed. The first one is to 
implement the \inlinecode{IPatternCheckerProvider} interface, defined in 
the assembly \emph{PatternEnfocer.Core.dll}. This interface contains one 
method \inlinecode{GetChecker}, which should return a constraints 
checker for the pattern. The last thing needed is to create the checker itself. 
The \inlinecode{FluentPatternChecker} class, which implements the DSL 
described in the subsection~\ref{subsec:constraintsapi}, 
is intended to be the base class for pattern checkers, 
although a minimal pattern checker has only to implement the 
\inlinecode{IPatternChecker} interface. The implementation of a checker for 
the \pattern{Base Caller} pattern is similar to the specification 
of the built-in patterns, which is described in the 
subsection~\ref{subsec:builtinpatterns}. 
For completeness of the example, 
figure~\ref{fig:basecallerchecker} shows the final implementation 
of the \pattern{Base Caller} pattern.
	\begin{figure}[h]				
		\begin{lstlisting}[language=C] %small listing
public class BaseCaller : IPatternCheckerProvider, ...
{
  // ... same as before    
  public IPatternChecker GetChecker() {
    return new Checker();
  }
  
  private class Checker : FluentPatternChecker<BaseCaller> {
    public Checker() {
      this.Type(pattern => pattern.TargetType)
          .Methods(method => method.OverridesBaseMethod())
          .Check((pattern, method) =>
                    method.GetMethodCalls() != null &&
                    method.GetMethodCalls().Any(call =>
                      call.HasTargetObject &&
                      call.TargetObject.IsThisParameter &&
                      call.Method.DeclaringType.IsEqual(
					      pattern.TargetBase) &&
                      call.Method.Name == method.Name),
                 (pattern, method) =>
                     string.Format(
                       "Method {0} does not invoke the base method.",
                       method.Name));
    }
  }
}
		\end{lstlisting}		
		\caption{Definition of the checker for the \pattern{Base Caller} pattern.}
		\label{fig:basecallerchecker}
	\end{figure}
	
\paragraph*{Addition of the \pattern{Base Caller} to Pattern Enforcer}
\subparagraph*{}
Finally Pattern Enforcer has to be informed that it should load the assembly 
that contain the custom pattern definition and search it for custom patterns 
definitions. For this purpose, it is required to provide the assembly 
location in a Pattern Enforcer configuration file. The configuration is an xml 
file (the \inlinecode{pattern-enforcer-config.xsd} file with definition of 
it's structure is supplied with Patterns4Net and included 
in the appendix~\ref{app:xsd}). The location of a configuration 
file is provided to Pattern Enforcer as a command line option, or the 
parameter of the MSBuild task.

%-------------------------------------------------------------------------------------------------
%-------------------------------------------------------------------------------------------------
%-------------------------------------------------------------------------------------------------
\section{Architecture}
\label{sec:enforcer-architecture}
In this section the architecture and the implementation of 
the common Patterns4Net infrastructure and Pattern Enforcer 
is discussed. We start with CIL parsing, because the instruments 
we use for this task influence the rest of the system. Then we 
describe design patterns representation and discovery architecture in 
more detail than at the beginning of this chapter. Our solution to CIL analysis 
and overall Pattern Enforcer design are also presented. In the last 
subsection, we provide basic information about the development infrastructure 
we used for the development of Patterns4Net.

%-------------------------------------------------------------------------------
%-------------------------------------------------------------------------------
\subsection{CIL processing}
\label{subsec:cil}
We have two basic options to process the source code of a .NET application 
or a library. The original textual source code can be parsed and represented as an 
abstract syntax tree (AST), or we can parse .NET assembly and use the 
Common Intermediate Language (CIL).

When the original source code is parsed and represented as an AST 
it is much easier to reconstruct 
higher level information such as actual parameters for a method invocation. 
On the other hand, available parsers not always support all of 
the most current language features and parsing of a source code of a 
specific language might restrict us to support 
the only one language. Some parsers are capable of parsing more source languages 
into the same AST structure, but the resulting AST is still different for 
some language specific constructs.

The other option, which we have chosen, is to analyze the intermediate 
language, in case of the .NET 
it is the Common Intermediate Language (CIL). The structure of CIL is more stable 
than, for example, the syntax of C\#. The latest version of CIL standard 
\cite{ecma2010tg3} from 2010 has the same instruction set as the previous 
version from 2006. The version from 2010 only extends semantics and 
verification rules for some of the instructions. Another advantage is 
that intermediate language is produced by all the compilers for .NET, 
thus Patterns4Net can be theoretically used also for Visual Basic.NET, 
IronRuby, IronPython and others, although we have tested it only on C\#. 
One of the disadvantages of this approach is that the CIL is stack based 
lower level language and the reconstruction of some constructs, such as actual 
parameters for a method invocation, requires special effort.

\paragraph{Library for CIL parsing}
\subparagraph*{}
There are three popular, publicly available libraries that could be used 
to parse .NET assemblies and get meta-data about types and CIL code of 
the methods. First option is to use the reflection API that is 
available as a part of the .NET base libraries. Second option is 
the Microsoft Common Compiler Infrastructure (CCI, \cite{cci:Online}), 
which is developed in Microsoft Research. 
Last option is Mono Cecil \cite{cecil:Online}, which is developed as a part of 
the Mono open-source project. 

Standard .NET Reflection API treats assemblies as a code, not as a raw data, 
which has two important consequences: the code loaded through the .NET Reflection 
API can be executed; and, because the code can be executed, the 
runtime must check access rights and might throw Code Access Security exception. 
Assemblies loaded into an AppDomain (a .NET object similar to an 
process in a operating system) cannot be unloaded, which means that after a long 
session with Architecture Explorer, when user have loaded many different assemblies, 
the process memory usage will be unnecessary high. Finally the .NET 
Reflection API does not distinguish between a type definition and a 
type reference, which is an entry in assembly meta-data 
referring to a type located in another 
assembly. If we used the standard Reflection API, there would be one 
notable advantage. In the public API of Patterns4Net, in some cases, 
we allow to use the .NET Reflection data structures in order to make the 
usage of the Patterns4Net API easier for developers used to use the 
.NET Reflection. However, because we internally use another library, 
we have to do a translation of the .NET Reflection data structures.

The other two libraries (CCI and Mono Cecil) process .NET assemblies 
as just a binary data, hence they do not support loading the assemblies 
into an AppDomain and execution of the loaded code. On the other hand 
they are claimed by their authors to be faster than the standard Reflection API, 
however, we are not aware of any serious benchmarks. Public API and features 
of CCI and Mono Cecil seem to be similar, except CCI provides AST over the 
intermediate language, which Mono Cecil doesn't 
provide\footnote{There is project Cecil Decompiler, but it is not in production ready quality.}. 
However, the AST generated by the CCI is more complex than we would need, 
therefore, for our purposes, the advantage of generated AST would be lessen 
by extra work for it's processing. Both of these two libraries have a 
long list of advanced software that use them. In case of Mono Cecil it 
is, for example, db4o (object database for java and .NET) or Mono C\# compiler. 
On the other side, FxCop (a bug-finding tool) or Code Contracts are both 
based on CCI.

Our previous experiences with Mono Cecil have resolved the choice between 
Mono Cecil and CCI in favor of Mono Cecil. This choice does 
not only influence the code that does the CIL analysis, but also other code,  
because we use specific Mono Cecil's data structures 
(e.g., \inlinecode{TypeReference}) in the whole Patterns4Net project. 

%-------------------------------------------------------------------------------
%-------------------------------------------------------------------------------	
\subsection{Patterns representation and discovery}
\label{subsec:patternsrepre}
Patterns representation is described in the section~\ref{sec:dpdocumentation}. 
Here we just remind that a pattern instance is represented as an object that 
provides references to the participants of this pattern instance. 
Mono Cecils structures are used for types and methods identification. 

The discovery of patterns meta-data is implemented as a flexible 
mechanism. There is a central class, which aggregates several objects and each of 
them provides a strategy for creation of the pattern participants mapping 
based on CIL metadata. The class hierarchy is show in the figure~\ref{fig:patternslocation}. 
\begin{figure}[h]
  \mbox{\includegraphics[width=120mm]{images/patterns-location.png}}
  \caption{Hierarchy of classes that are used for discovery of patterns meta-data.}
  \label{fig:patternslocation}
\end{figure}

There are two built-in strategies for the pattern participants mapping 
discovery. Both are based on pattern meta-data (additional information 
added to a .NET assembly by it's author in order to document patterns 
he has implemented). In both cases these meta-data are expressed as .NET 
attributes provided by Patterns4Net. These two strategies differ only 
in way they reconstruct the pattern participants mapping from attributes. 
Before we describe them in more detail, we discuss challenges connected 
with .NET attributes.

\paragraph*{Attributes based discovery}
\subparagraph*{}
When a class is annotated with an attribute, this information is projected 
into the meta-data located in the .NET assembly. These CIL meta-data are then 
parsed by Mono Cecil as a raw data, so it does not contain real instances of the 
classes that represent attributes, rather, Mono Cecil provides 
information about the type of the attribute, the values 
provided as it's constructor parameters and provided named arguments. 
If a user of Mono Cecil wants to reconstruct an identical instance 
of the attribute, he has to do it by hand. 

There are two basic options to solve the task of attributes reconstruction. 
The pattern attributes should always implement a 
constructor with name-value dictionary as a parameter. The constructor is 
expected to reconstruct the attribute instance from this dictionary and it 
is used to create attributes instances according to CIL meta-data. 
(This approach is also used in the MEF.) 
The other option is not to reconstruct the 
attribute instance at all, but for each attribute provide another 
strategy class that will create the pattern instance based on the 
attribute's CIL meta-data, but without instantiating the attribute. 

The reconstruction of an attribute using special constructor provided by the 
attribute is implemented in the \inlinecode{AttributesPatternsProvider} 
strategy class. It provides higher cohesion, because we don't have to 
create another strategy class for each attribute. The direct construction of 
pattern instances from CIL meta-data is implemented in 
the \inlinecode{PlainAttributesPatternProvider} strategy class.

\paragraph*{Attributes and pattern instances representation}
\subparagraph*{}
Since we wanted the mechanism of the discovery of the pattern participants 
mapping to be flexible, our representation of pattern instances must be 
independent of whether attributes or something else is used for their 
documentation. Therefore the classes that represent patterns, 
shouldn't have to represent the attributes 
for their documentation. There should be possibility decouple 
these two things.

Because the \inlinecode{PlainAttributesPatternProvider} strategy class 
constructs directly the design pattern instances, without constructing 
the attributes instances, there doesn't have to be any coupling between 
the pattern class and the attribute class. However, the 
\inlinecode{AttributesPatternProvider} class reconstructs the attribute 
instance and in order to take advantage of this instance we allow such 
attributes to provide a method which creates the pattern instance. 
In this case an additional strategy class for the construction of a pattern 
instance from the CIL meta-data is not needed, the strategy is 
implemented as method of the attribute, but it also means that the pattern and 
it's attribute are coupled. The approach implemented by the 
\inlinecode{PlainAttributesPatternProvider} class is used internally by 
Pattern Enforcer and the second one is intended to be used for 
implementation of user-defined custom patterns, because is it easier to use.

%-------------------------------------------------------------------------------
%-------------------------------------------------------------------------------
\subsection{CIL analysis}
Mono Cecil provides only data parsed from .NET assemblies, it does not provide 
anything more. From CIL meta-data we can, for example, determine for a 
given class what type is it's base type, or which interfaces it implements. 
But Cecil itself does not provide a method that would give us a list of 
types that implement given interface, because this information cannot be 
inferred directly from it's meta-data. For such purposes there is the 
Mono Cecil Rocks project, which contains a few extension methods for the Cecil's 
classes, but it does not have all we wanted to support in Patterns4Net, 
so we also implemented our custom set of extension methods designed for 
CIL analysis and patterns structure constrains specification.

For example, one of the extensions we wanted to provide was uniform API 
for getting information about methods overrides. In CIL, according to ECMA CIL 
specification~\cite{ecma2010tg3}, there is an attribute "overrides" in 
the meta-data of every method, which is a list of methods that this method overrides. 
But this attribute is used only in specific cases (e.g., explicit interface 
implementation) and normally it is left empty, because overridden methods 
are determined by conventions (which are also described in the ECMA CIL 
specification). 

\paragraph*{Methods invocation analysis}
\subparagraph*{}
For the purposes of the discovery of relationships in Architecture Explorer and 
methods invocations in Pattern Enforcer, we needed classes that would help us 
with analysis of CIL. We don't need to analyze conditional statements -- we 
just want to know whether a method M1 on a field F is invoked in body 
of a method M2, even in a dead branch of code.

Method calls in CIL are done by several instructions, for example 
\inlinecode{.callvirt}. CIL does not distinguish between instance methods 
and static methods. Instance methods has the instance as a first parameter, 
which is normally added by a compiler. Each of these instructions has a method 
reference as an operand, so the only difficulty is to analyze with which 
actual parameters the method was invoked.

The CIL virtual machine is a stack based machine, which means that all arguments 
for operations are taken from the evaluation stack and results are 
pushed onto the stack. Usually instructions pop all their arguments from the 
stack and push results onto the top. Stack behavior of each instruction is  
documented in the ECMA CIL specification, however, Cecil provides this 
information through the enumeration \inlinecode{StackBehaviour}. 

The CIL analysis is done by simulating the evaluation stack. In a loop we 
iterate over all instructions in the method body. For each instruction 
we determine how many items it pops from the stack and we determine, 
which items it pushes onto the stack. The stack is represented as 
a collection of instances of the \inlinecode{StackItem} class. 
Each \inlinecode{StackItem} has a reference to the instruction that 
resulted in pushing this item onto the stack, and with this basic information 
the \inlinecode{StackItem} can provide some more additional information such as 
whether it represents a field pushed onto the stack (if so, then which field), 
or a parameter aso. The result of this analysis is a collection of 
the \inlinecode{StackState} class instances -- n-th of them represents 
the state of the stack after the execution of n-th instruction in the method body. 
State of the stack is represented as a collection of \inlinecode{StackItem} instances.
From the signature of the method we know how many parameters it has 
(we will designate it as $m$) and whether it is an instance method 
or a static method. To get the actual parameters of a specific call 
instruction (say it's $n$-th instruction), we just need to take 
$m$ (or $m+1$ for instance methods, which have implicit first parameter) 
items from the top of the $n-1$-th \inlinecode{StackState}.

The last question may be whether this correctly simulates the stack 
if we do not take the control flow instructions into account (only their stack 
behavior). The answer is provided by ECMA CIL specification, which reads
\begin{quotation}
Regardless of the control flow that allows execution to arrive there, 
each slot on the stack shall have the same data type at any given point 
within the method body.
\end{quotation}

\paragraph*{CIL instructions sequences matching}
\subparagraph*{}
In order to check some more specific constraints such as the specification 
for the \pattern{Singleton} pattern implementation, we need to check whether 
a method body contains a specific CIL instructions sequence. 

The aim here was to be able to match sequence which, for example, 
contains anything at the beginning and then it contains a sequence of 
instructions that represents an \inlinecode{if} with a specific condition. 
For this purpose the matching process is directed by one object that 
delegates its work to several strategy objects that do the actual matching. 
In our example, we would have a strategy that would match any instruction 
and a strategy that would match the instructions sequence that represents 
an \inlinecode{if}.

The main class for CIL instructions sequences matching is 
the \inlinecode{CILPatternsMatcher}. It aggregates a collection of instances of 
the \inlinecode{InstructionMatcher} abstract class, 
which represents an instructions sequence. 
Interface of the \inlinecode{InstructionMatcher} class 
is shown in figure~\ref{fig:instructionmatcher}. 
The \inlinecode{Matches} method is called in a loop provided with current 
instruction. If the method returns \inlinecode{false}, than the 
CIL instructions does not match the expected sequence and the whole process 
ends with a negative result. Otherwise property \inlinecode{Found} is checked 
and if \inlinecode{true}, then the next \inlinecode{InstructionMatcher} is used in 
the next iteration, if it was the last \inlinecode{InstructionMatcher}, then 
process ends with success. In the next iteration current instruction is set to 
the one returned by last call of \inlinecode{Match}. A pseudo code is given in 
the figure~\ref{fig:matcherpseudocode}, variable \inlinecode{matchers} represents 
an array of the \inlinecode{InstructionMatcher} class instances.
	\begin{figure}[h]
		\begin{lstlisting}[language=C]
public abstract class InstructionMatcher
{
	public virtual bool Found { get; protected set; }
	public abstract bool Matches(
		Instruction instruction, 
		out Instruction next);
	public virtual void Reset() { ... }
}
		\end{lstlisting}
		\caption{The \inlinecode{InstructionMatcher} abstract class interface.}
		\label{fig:instructionmatcher}
	\end{figure}
	
	\begin{figure}[h]
		\begin{algorithmic}[1]
			\STATE $currentInstruction \gets$ first instruction of the method's body.
			\STATE $currentMatcherIdx \gets 0$
			\LOOP
				\STATE $matcher \gets matchers[currentMatcherIds]$
				\STATE $match \gets matcher.Match(currentInstruction, out\;next)$
				\IF{$not$ $match$}
					\RETURN $false$
				\ENDIF
				\IF{$matcher.Found$}
					\IF{$++currentMatcherIdx == matchers.Length$}
						\RETURN $true$
					\ENDIF
				\ENDIF
				\STATE $currentInstruction \gets next$
			\ENDLOOP
		\end{algorithmic}	
		\caption{Pseudo code of CIL instructions patterns matching.}
		\label{fig:matcherpseudocode}		
	\end{figure}	

	
%-------------------------------------------------------------------------------
%-------------------------------------------------------------------------------
\subsection{Pattern Enforcer Design}
The basic interface in the Pattern Enforcer design is the generic 
\inlinecode{IChecker<T>} interface, which defines one method 
\inlinecode{Check(T)}. This method returns the result of the 
check encapsulated in an instance of the \inlinecode{CheckerResult} 
class. Concrete checkers have the generic parameter \inlinecode{T} 
set to the \inlinecode{TypeDefinition} class, 
the \inlinecode{MethodDefinition} class or the \inlinecode{IPattern} interface.

An important class is the \inlinecode{FluentPatternChecker}. It is a base 
class of most of the pattern checkers, because it provides the structural 
constraints specification API. The API is formed by protected methods of 
the \inlinecode{FluentPatternChecker} class, which should be invoked in the 
constructor of a derived class in order to specify the constraints. 
Because we wanted to provide a Fluent interface (chaining of method calls), 
we have to remember the parameters of chained methods, so the last method 
in the chain can access all of them and perform the desired action.
For this purpose each chained method returns special objects that have 
\begin{itemize}
	\item{a reference to the parent object (an object on which 
the method was invoked)  and}
	\item{the values of the arguments the method was invoked with.}
\end{itemize}
For the first method in a chain the parent object is the checker instance itself, 
for others, it is a object returned by their ancestor method 
in the chain. As the method calls are chaining the arguments are collected 
and the last method in the chain, which is the first method that wil actually 
do something, has all the arguments of previous methods available to do 
it's work. The example of such chaining of methods is given in the 
figure~\ref{fig:chaining}.
	\begin{figure}[h]				
		\begin{lstlisting}[language=C]
this.Type(pattern => pattern.PatternRoleType)	
  .Methods(method => method.IsPublic || method.IsProtected) 
  .Check((pattern, method) => method.Name.EndsWith("42"),
		(pattern, method) => "Method has not a valid name");
		\end{lstlisting}		
		\caption{An example of methods chaining.}
		\label{fig:chaining}
	\end{figure}

The whole Pattern Enforcer is encapsulated as the \inlinecode{PatternEnforcer} 
class. It requires a \inlinecode{PatternsLocator} instance and an array of 
\inlinecode{IPatternCheckersLocator} instances.

%-------------------------------------------------------------------------------
%-------------------------------------------------------------------------------
\subsection{Development infrastructure}
In this section about Pattern Enforcer architecture, we also describe 
common infrastructure used by both Pattern Enforcer and Architecture Explorer 
tools. Patterns4Net tools are developed in the .NET platform version 4.0, 
mostly in the C\# 4.0 language. Xml technologies are also used. 
All xml formats have their corresponding xsd file.

\paragraph{Visual Studio solution layout}
\subparagraph{}
In the figure~\ref{fig:solution} we can see the layout of the Visual Studio 
solution used for Patterns4Net development. When we refer to the 
projects from this solution in the following text, 
we will omit the \emph{Patterns4Net} prefix.
\begin{figure}[h]
  \mbox{\includegraphics[width=65mm]{images/solution.png}}
  \caption{The layout of Visual Studio solution.}
  \label{fig:solution}
\end{figure}

The projects that start with "PaternEnforcer" are related to 
Pattern Enforcer tool. The classes that provide the core functionality of 
Pattern Enforcer and the classes that form the unit-testing public API are 
located in the \patternsproj{PatternEnforcer.Core} project. 
The output of the \patternsproj{PatternEnforcer.Cmd} project is 
a command line interface for Pattern Enforcer and the project 
\patternsproj{PatternEnforcer.MSBuildTask} is 
the implementation of the task for the MSBuild engine. The core functionality and 
the unit-testing API of Pattern Enforcer are decoupled from the command line interface 
and the MSBuild task into separate project, and thus separate assembly, 
because the Pattern Enforcer core functionality is also used in 
the \patternsproj{ArchitectureExplorer} project. The resulting 
assembly with the Pattern Enforcer core functionality is also meant 
to be referenced by users in their unit-testing 
projects and if it had an .exe suffix, although perfectly valid assembly 
that can be referenced, an unusual suffix might confuse some users.

The \patternsproj{ArchitectureExplorer} project contains the code 
of Architecture Explorer GUI tool. The GUI is done in Windows Presentation 
Foundation (WPF) framework. In this project, besides C\# classes, also 
XAML\footnote{Extensible Application Markup Language} files are included.

Automated tests are used during the development of Patterns4Net. These 
tests are located in the \patternsproj{Tests} project. 
This project aggregates tests for the classes from all the other projects, 
because we don't need to separate the tests into several projects 
and a lower number of projects speeds up the build process. 

The classes that deal with the discovery of patterns meta-data and 
the patterns representation are located 
in the \patternsproj{Core} project. 
Although we use only Patterns4Net attributes at the moment, 
process of discovering patterns meta-data for classes and methods is 
extensible. 

Finally, the \patternsproj{Patterns} project contains only 
the classes that represent the Patterns4Net attributes. These classes 
inherit from \inlinecode{System.Attribute} class and they are very simple, 
hence we don't necessarily need to take advantage of the advanced features of 
C\# 4.0. This enables us to set the target framework version to 2.0, which 
means that the resulting assembly can be referenced and used 
by older .NET projects as well.

\paragraph{General principles}
\subparagraph{Automated tests.} 
Every software should be tested. Besides manual testing, usually a time 
consuming task, there is also the possibility to automate some tests, 
which means that their execution is controlled by a software and 
the software reports eventual errors. Execution of such tests lasts 
in seconds, so they can be executed quite often. Some of the code of 
Patterns4Net is tested this way. For automated tests the NUnit framework 
\cite{nunit:Online} is used. 

\subparagraph*{Extensibility.}
For better support of extensibility the Managed Extensibility 
Framework (MEF, \cite{mef:Online}) is used. 
Most of the classes in Patterns4Net get their dependencies as constructor 
arguments so the composition of all the objects by hand would be tedious. 
Instead the composition capabilities of the MEF are employed. 
A type whose instance should be used anywhere the interface \inlinecode{IFace} 
is expected must be decorated with attribute 
\inlinecode{[Export(typeof(IFace))]}, the dependencies of such type will be 
resolved by MEF recursively. Because assemblies with custom 
patterns loaded by Pattern Enforcer are also added 
to the MEF composition process, users can add custom plugins, 
for example, custom implementation of \inlinecode{IPatternsProvider}. 
However, this experimental feature was not extensively tested and 
is not further documented.

\subparagraph*{Code Contracts.} 
Most of the classes define their contracts using 
Microsoft Code Contracts~\cite{code-contracts:Online}. 
Contracts help us to find the issues earlier. 
An exception is typically thrown during the pre-conditions check, which is 
the real cause of the problem, rather than later on the source code line 
that expects valid input parameters. Code Contracts also serve as a complement 
to the API documentation.

\subparagraph*{Design Patterns.} Patterns4Net can be considered as a 
first example of it's own usage, because Patterns4Net code is annotated 
with patterns attributes.

%-------------------------------------------------------------------------------------------------
%-------------------------------------------------------------------------------------------------
%-------------------------------------------------------------------------------------------------
\section{Comparison}
There are several existing tools that provide verification of 
design patterns implementation. The most similar approach to Pattern Enforcer 
is the Pattern Enforcing Compiler (PEC) for Java. 

\subsection{FxCop and Gendarme tools.}
It may not be obvious, but Pattern Enforcer is similar 
to static analysis bug-hunting tools such as FxCop \cite{fxcop:Online} 
or Gendarme \cite{gendarme:Online}. These tools 
search the source code for the idioms that are generally considered as bad. For 
example strings should be, in most cases, compared using 
\inlinecode{string.CompareOrdinal}, but not using \inlinecode{==} operator. 
There are two main differences between Pattern Enforcer and these tools
\begin{itemize}
	\item{Pattern Enforcer checks only the code that is annotated,}
	\item{Pattern Enforcer checks structural aspects and code idioms, 
	but Gendarme and FxCop check only code idioms.}
	\item{Gendarme and FxCop are looking for bad idioms, but 
	Pattern Enforcer verifies that expected idiom is present.}
\end{itemize}

Gendarme is open-source tool that is meant to be an alternative to FxCop. 
It uses Mono Cecil for CIL analysis. If we look at Gendarme's source code, 
it has a similar structure to Pattern Enforcer's code. 
It has also "checker" classes, that perform checks on a code element,  
which might be, for example, Cecil's \inlinecode{TypeDefinition}. 

\subsection{Pattern Enforcing Compiler (PEC) for Java}
Because the Pattern Enforcing Compiler (PEC) for Java~\cite{lovatt2007pattern} 
has been the main source of an inspiration for our thesis, we discuss it a 
little bit more in detail. 

PEC for Java is an extended Java compiler that formalizes patterns. 
Developers can use standard Java syntax to annotate their classes as an 
implementation of specific design pattern. The PEC then checks whether 
the classes actually implement the specified patterns.

\subparagraph*{Annotation.} For annotation of patterns instances, 
PEC uses so called marker interfaces. The authors have chosen this technique, 
because implemented interfaces are listed in generated API documentation 
and so an integration with an API documentation didn't require any 
additional work to be done. On contrary, interfaces can only be used for 
annotation of classes, but not methods, and even when interfaces can have 
arguments -- generic arguments --, these can capture only a limited number 
of additional information. The authors of PEC admit these weaknesses of 
interfaces as a technique for the annotation of patterns and 
in~\cite{lovatt2007pattern}, they propose to introduce the standard 
java annotations, similar to .NET attributes, in PEC. However, 
we are not aware of any updated version of PEC that uses 
standard Java annotations.

\subparagraph*{Pattern Enforcement.}
PEC uses static analysis and it also enforces the rules dynamically by 
inserting assertions into the resulting program, which we don't support 
in our Pattern Enforcer. Dynamical enforcement 
provides more accurate results, because, for example, uniqueness of 
the one \pattern{Singleton} instance cannot be proved statically, but one simple 
assertion in it's constructor is enough to enforce it dynamically. 
The disadvantage of dynamical enforcement is that it slows down the resulting 
program and the program still has to be manually tested in order 
to discover possible bugs.

\subparagraph*{Code generation.}
PEC provides also code generation capabilities. For example, a body of a void method 
in a \pattern{Composite} class can be generated by PEC -- it just 
creates a loop over all components and on each of them it invokes the 
corresponding method. However, an implementation of the \pattern{Composite} 
pattern is usually not so straightforward, so these capabilities turn to be not 
so useful.

\subparagraph*{Patterns specification.}
Two APIs for patterns specification are supported in PEC. It is the standard 
Java reflection API and Javaasist, which is similar to Mono Cecil. In Pattern 
Enforcer we support the standard .NET reflection only partly. In PEC a method 
that checks a pattern implementation must be a static method with specific signature 
declared in a marker interface of the pattern. This introduces coupling 
between a pattern annotation and a pattern enforcement, which we tried to 
avoid in Patterns4Net. PEC uses exceptions to to signal the errors during 
the check of pattern implementation. This means that usually when a first 
violation is found, an exception is thrown and the verification process does 
not continue. In our Pattern Enforcer we use a return value of the special type 
\inlinecode{CheckerResult} as the result of the check and this 
object can aggregate more errors.

\subparagraph*{Integration with development environment.}
The authors of PEC claim that it is an extended compiler, which means that 
Java source code is compiled only with PEC, although PEC internally uses 
\inlinecode{javac}. This provides a seamless integration with the Java 
environment, but at the same moment PEC becomes an essential requirement for 
successful build. Our Pattern Enforcer is standalone tool, which can be 
easily taken out from the build process. PEC does not provide any other 
usage possibilities, but our Pattern Enforcer has the MSBuild task and 
the unit-testing API.

\subsection{Other tools}
CoffeeStrainer \cite{bokowski1999coffeestrainer} is a tool that is somewhere 
between static analysis bug-hunting tools whose objects of interest are idioms, 
smaller pieces of code, and pattern enforcement tools. Unlike other 
static analysis bug-hunting tools CoffeeStrainer enforces rules that result 
from particular design decisions, for this it provides means for custom 
rules specification. CoffeeStrainer targets the Java platform.

Pattern-Lint \cite{sefika1996monitoring} can check conformance to variety 
of design principles from coding style rules to design patterns. 
Pattern-Lint targets C++ and has been successfully evaluated during development 
of a multimedia operating system.

Most of the approaches described in~\cite{taibi2007design} are connected with 
some prototype tool that enforces the specification represented according to 
the formalization approach. 
However, most of them are not publicly available and all of them target 
either Java or C++ languages. The most interesting tools from this book include 
the HEDGEHOG engine, which we also discuss in the section~\ref{sec:patterns-formalization}, 
and tools that come with LePUS3, which we also present in the same section. 

To close this section, we can conclude that we are not aware of any design 
patterns verification tool for the .NET platform. Pattern Enforcer is, 
among all of these tools, also extraordinary with it's special C\# API for 
structural constraints specification, because most of the other approaches 
uses special language for patterns formalization, or, in case of 
the Pattern Enforcing Compiler for Java, they don't 
provide special means for structural constraints specification at all.

